const express = require('express');
const router = express.Router();
const { Course, Category, User, Chapter } = require('../../models')
const { Op } = require('sequelize')
const { success, failure } = require('../../utils/responses');
const { NotFoundError } = require('../../utils/errors')

//查询课程列表
router.get('/', async function (req, res) {
    try {
        const query = req.query
        // 当前页数，如果不传值默认第一页
        const currentPage = Math.abs(Number(query.currentPage)) || 1
        // 每页显示的数量，如果不传值默认10
        const pageSize = Math.abs(Number(query.pageSize)) || 10
        //计算offset
        const offset = (currentPage - 1) * pageSize

        const condition = {
            ...getCondition(),
            order: [['id']],
            limit: pageSize,
            offset: offset
        }

        if (query.categoryId) {
            condition.where = {
                categoryId: {
                    [Op.eq]: query.categoryId
                }
            }
        }
        if (query.userId) {
            condition.where = {
                userId: {
                    [Op.eq]: query.userId
                }
            }
        }
        if (query.name) {
            condition.where = {
                name: {
                    [Op.like]: `%${query.name}%`
                }
            }
        }
        if (query.recommended) {
            condition.where = {
                recommended: {
                    //转为布尔值
                    [Op.eq]: query.recommended === 'true'
                }
            }
        }
        if (query.introductory) {
            condition.where = {
                introductory: {
                    //转为布尔值
                    [Op.eq]: query.introductory === 'true'
                }
            }
        }

        const { count, rows } = await Course.findAndCountAll(condition)
        success(res, '课程查询成功', {
            courses: rows,
            pagination: {
                total: count,
                currentPage,
                pageSize
            }
        })
    } catch (error) {
        failure(res, error)
    }

})
//查询课程详情
router.get('/:id', async function (req, res) {
    try {
        const course = await getCourse(req)
        success(res, '查询课程成功', { course })

    } catch (error) {
        failure(res, error)
    }

})

//创建课程
router.post('/', async function (req, res) {
    try {
        //创建白名单过滤
        const body = filterBody(req)
        body.userId = req.user.id
        const course = await Course.create(body);
        //200和201都表示成功,201表示创建新的资源
        success(res, '创建课程成功', { course }, 201)
    } catch (error) {
        failure(res, error)
    }
})

//删除课程
router.delete('/:id', async function (req, res) {
    try {
        const course = await getCourse(req)
        const count = await Chapter.count({ where: { courseId: req.params.id } })
        if (count > 0) {
            throw new Error('该课程下存在章节，不能删除')
        }
        await course.destroy()
        success(res, '删除课程成功')
    } catch (error) {
        failure(res, error)
    }
})

//更新课程
router.put('/:id', async function (req, res) {
    try {
        const course = await getCourse(req)

        //创建白名单过滤
        const body = filterBody(req)

        //更新课程
        await course.update(body)
        success(res, '更新课程成功', { course })

    } catch (error) {
        failure(res, error)
    }
})

//关联分类
function getCondition() {
    return {
        attributes: { exclude: ['CategoryId', 'UserId'] },
        include: [
            {
                model: Category,
                as: 'category',
                attributes: ['id', "name"]
            },
            {

                model: User,
                as: 'user',
                attributes: ['id', 'username', 'avatar']
            }
        ]
    }
}

//查询当前课程：公共方法
async function getCourse(req) {
    //获取课程ID
    const { id } = req.params
    const condition = getCondition()
    //查询当前课程ID
    const course = await Course.findByPk(id, condition)

    //如果课程不存在，抛出错误异常
    if (!course) {
        throw new NotFoundError(`ID:${id}课程不存在`)
    }
    return course
}

// 白名单过滤：公共方法
function filterBody(req) {
    return {
        categoryId: req.body.categoryId,
        name: req.body.name,
        image: req.body.image,
        recommended: req.body.recommended,
        introductory: req.body.introductory,
        content: req.body.content
    }
}
module.exports = router;